import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../aes/aes_utils.dart';
import 'user_manager.dart';
import 'test_http.dart';

// 登录状态 Provider
final authStateProvider = StateNotifierProvider<AuthNotifier, AuthState>((ref) {
  return AuthNotifier();
});

// 登录状态类
class AuthState {
  final bool isLoggedIn;
  final bool isLoading;
  final LoginTokenModel? user;
  final String? error;

  const AuthState({
    this.isLoggedIn = false,
    this.isLoading = false,
    this.user,
    this.error,
  });

  AuthState copyWith({
    bool? isLoggedIn,
    bool? isLoading,
    LoginTokenModel? user,
    String? error,
  }) {
    return AuthState(
      isLoggedIn: isLoggedIn ?? this.isLoggedIn,
      isLoading: isLoading ?? this.isLoading,
      user: user ?? this.user,
      error: error ?? this.error,
    );
  }
}

// 登录状态管理器
class AuthNotifier extends StateNotifier<AuthState> {
  AuthNotifier() : super(const AuthState()) {
    _checkLoginStatus();
  }

  // 检查登录状态
  Future<void> _checkLoginStatus() async {
    state = state.copyWith(isLoading: true);
    try {
      final isLoggedIn = await UserManager.isLoggedIn();
      final user = await UserManager.getLoginInfo();
      state = state.copyWith(
        isLoggedIn: isLoggedIn,
        user: user,
        isLoading: false,
        error: null,
      );
    } catch (e) {
      state = state.copyWith(isLoading: false, error: e.toString());
    }
  }

  // 登录
  Future<void> login(String accountName, String password) async {
    state = state.copyWith(isLoading: true, error: null);

    try {
      final userResponse = await HttpUtil().postModel(
        'ComicMember/Login',
        data: {
          'accountName': accountName,
          'passWord': password,
          'loginType': AESUtil.encryptECB('0'),
          'platformId': 1,
        },
        fromJson: LoginTokenModel.fromJson,
      );

      if (userResponse?.status == 200 && userResponse?.result != null) {
        // 保存登录信息
        await UserManager.saveLoginInfo(userResponse!.result!);

        state = state.copyWith(
          isLoggedIn: true,
          user: userResponse.result,
          isLoading: false,
          error: null,
        );
      } else {
        state = state.copyWith(
          isLoading: false,
          error: userResponse?.message ?? '登录失败',
        );
      }
    } catch (e) {
      state = state.copyWith(isLoading: false, error: e.toString());
    }
  }

  // 退出登录
  Future<void> logout() async {
    state = state.copyWith(isLoading: true);

    try {
      await UserManager.clearLoginInfo();
      state = const AuthState(isLoggedIn: false, isLoading: false);
    } catch (e) {
      state = state.copyWith(isLoading: false, error: e.toString());
    }
  }

  // 刷新登录状态
  Future<void> refresh() async {
    await _checkLoginStatus();
  }
}
